package com.site.util.listener;

/**
 * ApplicationServlet.java
 * Product:BaseLayer
 * Version:1.0
 * Copyright 2009 by DNE
 * All Rights Reserved.
 */



import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.site.util.CodeMapDBUtil;
import com.site.util.LocaleMapManager;
import com.site.util.PropertiesFactory;
import com.site.util.PropertyUtil;
import com.site.util.StringUtils;
import com.site.util.constant.Constants;


/**
 * 应用启动时，初始化一些数据
 */
public class ApplicationListener implements ServletContextListener {
	private Log log=LogFactory.getLog(this.getClass());
	
	/*
	 * (non-Javadoc)
	 * 
	 * @seejavax.servlet.ServletContextListener#contextDestroyed(javax.servlet.
	 * ServletContextEvent)
	 */
	public void contextDestroyed(ServletContextEvent arg0) {
		// TODO Auto-generated method stub

	}
	
	private void loadSystemConfig(ServletContextEvent event) {
		log.info("加载系统属性文件 开始...");
		new PropertiesFactory().init(); 
		String configPath=event.getServletContext().getInitParameter(Constants.SITE_CONFIGPATH);
		if(!StringUtils.isEmpty(configPath)){
			PropertiesFactory.configPath=event.getServletContext().getRealPath(configPath)+"/";
		}else{
			PropertiesFactory.configPath=PropertiesFactory.get("baselayer.config.path");
		}
		log.info("加载系统属性文件 结束...");
	}
	
	private void loadPropertyConfig(ServletContextEvent event){
		//将所有的property存储到context中
		event.getServletContext().setAttribute(Constants.PROPERTY_NAME,new PropertyUtil().getAllProperty(event.getServletContext()));
	}
	private void loadMessageConfig(ServletContextEvent event) throws Exception {
		
		log.info("国际化资源文件初始化开始...");
		event.getServletContext().setAttribute(Constants.APPLICATION_COMMON_XML,new LocaleMapManager().initMap());
		log.info("国际化资源文件初始化完成...");
	}
	private void loadCodeConfig(ServletContextEvent event){
		//将所有的code存储到context中
		event.getServletContext().setAttribute(Constants.CODE_MAP_NAME,new CodeMapDBUtil().getAllCode(event.getServletContext()));
	}
	@Override
	public void contextInitialized(ServletContextEvent event) {
		try {
			// 加载系统属性文件（需要首先加载）
			loadSystemConfig(event);
			// 初始化属性
			 loadPropertyConfig(event);
			// 国际化资源文件初始化
			loadMessageConfig(event);
			// 编码的初始化
			loadCodeConfig(event);
		} catch (Exception e) {
			e.printStackTrace();
		}		
	}
}
